﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace WpfLearn
{
    public class TextBoxHelper
    {
        static TextBoxHelper()
        {
            HasTextProperty = HasTextPropertyKey!.DependencyProperty;
        }

        public static bool GetHasText(DependencyObject obj)
        {
            return (bool)obj.GetValue(HasTextProperty);
        }

        protected static void SetHasText(DependencyObject obj, bool value)
        {
            //不能直接设置HasTextProperty，而应该设置HasTextPropertyKey
            obj.SetValue(HasTextPropertyKey, value);
        }

        public static readonly DependencyProperty HasTextProperty;
        public static readonly DependencyPropertyKey HasTextPropertyKey =
            DependencyProperty.RegisterAttachedReadOnly(
                "HasText", 
                typeof(bool), 
                typeof(TextBoxHelper), 
                new PropertyMetadata(false));


        public static bool GetMonitorTextChange(DependencyObject obj)
        {
            return (bool)obj.GetValue(MonitorTextChangeProperty);
        }

        public static void SetMonitorTextChange(DependencyObject obj, bool value)
        {
            obj.SetValue(MonitorTextChangeProperty, value);
        }

        /// <summary>
        /// 只有设置默认值为false，当设置为true的时候才会立
        /// 刻触发MonitorTextChangePropertyChanged事件
        /// </summary>
        public static readonly DependencyProperty MonitorTextChangeProperty =
            DependencyProperty.RegisterAttached(
                "MonitorTextChange", 
                typeof(bool), 
                typeof(TextBoxHelper), 
                new PropertyMetadata(false, MonitorTextChangePropertyChanged));

        private static void MonitorTextChangePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is not TextBox box) throw new NotSupportedException();
            if ((bool)e.NewValue)
            {
                box.TextChanged += TextChanged;

                //如果TextBox中本来就有值，则不会触发TextChanged事件
                //所以需要提前判断一下
                SetHasText(box, !string.IsNullOrEmpty(box.Text));
            }
            else
            {
                box.TextChanged -= TextChanged;
            }
        }

        private static void TextChanged(object sender, TextChangedEventArgs e)
        {
            //能到这里来的sencer一定是TextBox
            var box  = sender as TextBox;
            SetHasText(box!, !string.IsNullOrEmpty(box!.Text));
        }
    }//end of class
}
